{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.312c1fae579076e0074e5503665c8d15.315360000.1910288601.282335-21429165', 'expires_in': 2592000, 'session_key': '9mzdCSWy3xiLS26Emtee0eAOAQlNJYkpbX2HN4oN5hFXGoqO4BR8QQY5Yd+imBmg1Wk9B5eRnW5bLdc4fcLnxO4HkyLatQ==', 'access_token': '24.2347a797a8c284fed0df73f6bf89d435.2592000.1597520601.282335-21429165', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理', 'session_secret': '11de74d71771113f609b3c713b55ce3e'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=3MWovLDBlcUD6Md1sB8SVfvY&client_secret=OgbuaT2KEgacN7UVa1wGf5VtFncGhkI6'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'log_id': 4083519078065625585, 'result': [{'score': 0.4277234375476837, 'name': '刺葵'}, {'score': 0.28552478551864624, 'name': '油棕'}, {'score': 0.24210301041603088, 'name': '海枣'}]}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('梧桐.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.2347a797a8c284fed0df73f6bf89d435.2592000.1597520601.282335-21429165'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ERROR: Could not find a version that satisfies the requirement tencentcloud.common (from versions: none)\n",
      "ERROR: No matching distribution found for tencentcloud.common\n",
      "WARNING: You are using pip version 20.1; however, version 20.1.1 is available.\n",
      "You should consider upgrading via the 'd:\\python\\python.exe -m pip install --upgrade pip' command.\n"
     ]
    }
   ],
   "source": [
    "pip install tencentcloud.common"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'log_id': 4191235455760514705, 'result': [{'score': 0.4277234375476837, 'name': '刺葵'}, {'score': 0.28552478551864624, 'name': '油棕'}, {'score': 0.24210301041603088, 'name': '海枣'}]}\n",
      "{'refresh_token': '25.efc154bce47635044f408547cfe09cc3.315360000.1910293881.282335-17924750', 'expires_in': 2592000, 'session_key': '9mzdWuq8kpafJ2kdSb4NbwloOCrslBq7vqStI+yzP1saW/1BucECMH//KmMXwOHwlVIEMuPEyCtb9lo69crsBrcNPUYgJA==', 'access_token': '24.a610393fb638cee83b8d6de678c2a837.2592000.1597525881.282335-17924750', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理', 'session_secret': 'e7549e8a14cd8f1302919ed115d38d8d'}\n",
      "fetch token begin\n",
      "{\"access_token\":\"24.870c02803aefd7a5148ab5ade4468dd7.2592000.1597525883.282335-21429832\",\"session_key\":\"9mzdA508Ns8AjRLEiHXYBLqYeruougG5XxmbA1HK9+Flpkx1y6bEaiVSSz93Lvyk0ufXTbM2hCF8oKMc0wmzpE8QMljYGA==\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope picchain_test_picchain_api_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406\",\"refresh_token\":\"25.2ba1756c861658b664e81e7f6d1954ea.315360000.1910293883.282335-21429832\",\"session_secret\":\"fb378f401ce4757ffb2e829ada68cf08\",\"expires_in\":2592000}\n",
      "\n",
      "{'access_token': '24.870c02803aefd7a5148ab5ade4468dd7.2592000.1597525883.282335-21429832', 'session_key': '9mzdA508Ns8AjRLEiHXYBLqYeruougG5XxmbA1HK9+Flpkx1y6bEaiVSSz93Lvyk0ufXTbM2hCF8oKMc0wmzpE8QMljYGA==', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope picchain_test_picchain_api_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理', 'refresh_token': '25.2ba1756c861658b664e81e7f6d1954ea.315360000.1910293883.282335-21429832', 'session_secret': 'fb378f401ce4757ffb2e829ada68cf08', 'expires_in': 2592000}\n",
      "%E6%A2%A7%E6%A1%90\n",
      "test on Web Browserhttp://tsn.baidu.com/text2audio?tok=24.870c02803aefd7a5148ab5ade4468dd7.2592000.1597525883.282335-21429832&tex=%25E6%25A2%25A7%25E6%25A1%2590&per=4&spd=5&pit=5&vol=5&aue=3&cuid=123456PYTHON&lan=zh&ctp=1\n",
      "result saved as :result.mp3\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# coding: utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('梧桐.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.2347a797a8c284fed0df73f6bf89d435.2592000.1597520601.282335-21429165'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())\n",
    "\n",
    "\n",
    "\n",
    "# 调用token\n",
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=ePM54d7oGji4jfGKVAMNZAct&client_secret=lSzTRUvqGHsq5Pd42XaH8VhEXB7IcRXk'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())\n",
    "\n",
    "\n",
    "# # 百度AI植物识别API\n",
    "\n",
    "\n",
    "\"\"\" 读取图片 \"\"\"\n",
    "def get_file_content(filePath):\n",
    "    with open(filePath, 'rb') as fp:\n",
    "        return fp.read()\n",
    "\n",
    "image = get_file_content('梧桐.png')\n",
    "\n",
    "\n",
    "\n",
    "# #  百度AI语音合成API\n",
    "\n",
    "\n",
    "from aip import AipSpeech\n",
    "\n",
    "\"\"\" 你的 APPID AK SK \"\"\"\n",
    "APP_ID = '21429165'\n",
    "API_KEY = '3MWovLDBlcUD6Md1sB8SVfvY'\n",
    "SECRET_KEY = 'OgbuaT2KEgacN7UVa1wGf5VtFncGhkI6 '\n",
    "\n",
    "client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "result  = client.synthesis('你好百度', 'zh', 1, {\n",
    "    'vol': 5,\n",
    "})\n",
    "\n",
    "# 识别正确返回语音二进制 错误则返回dict 参照下面错误码\n",
    "if not isinstance(result, dict):\n",
    "    with open('auido.mp3', 'wb') as f:\n",
    "        f.write(result)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# # 百度AI通用物体识别API\n",
    "\n",
    "\n",
    "from aip import AipImageClassify\n",
    "\n",
    "\"\"\" 你的 APPID AK SK \"\"\"\n",
    "APP_ID = '17924750'\n",
    "API_KEY = 'ePM54d7oGji4jfGKVAMNZAct'\n",
    "SECRET_KEY = 'lSzTRUvqGHsq5Pd42XaH8VhEXB7IcRXk'\n",
    "\n",
    "client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)\n",
    "\n",
    "\"\"\" 读取图片 \"\"\"\n",
    "def get_file_content(filePath):\n",
    "    with open(filePath, 'rb') as fp:\n",
    "        return fp.read()\n",
    "\n",
    "image = get_file_content('梧桐.png')\n",
    "\n",
    "\"\"\" 调用通用物体识别 \"\"\"\n",
    "client.advancedGeneral(image);\n",
    "\n",
    "\"\"\" 如果有可选参数 \"\"\"\n",
    "options = {}\n",
    "options[\"baike_num\"] = 5\n",
    "\n",
    "\"\"\" 带参数调用通用物体识别 \"\"\"\n",
    "client.advancedGeneral(image, options)\n",
    "\n",
    "\n",
    "# # 百度语音合成API\n",
    "\n",
    "\n",
    "from aip.speech import AipSpeech\n",
    "# from aip import AipSpeech\n",
    "\n",
    "\"\"\" 你的 APPID AK SK \"\"\"\n",
    "APP_ID = '17924750'\n",
    "API_KEY = 'ePM54d7oGji4jfGKVAMNZAct'\n",
    "SECRET_KEY = 'lSzTRUvqGHsq5Pd42XaH8VhEXB7IcRXk'\n",
    "\n",
    "client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "API_KEY = 'MaEg5X2xgLCwoYgtwB98T9oQ'\n",
    "SECRET_KEY = 'rpHWn4517ihiuYTUrqPCAr1SFm1cduGz'\n",
    "\n",
    "TEXT = \"梧桐\"\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 4\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 5\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 5\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 5\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 3\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'\n",
    "SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力，没有请在网页里勾选\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    print(\"fetch token begin\")\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req, timeout=5)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    \n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        #print(SCOPE)\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "       # print('SUCCESS WITH TOKEN: %s  EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "    \n",
    "#     if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "#         if not SCOPE in result['scope'].split(' '):\n",
    "#             raise DemoError('scope is not correct')\n",
    "#         print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "#         return result['access_token']\n",
    "#     else:\n",
    "#         raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode\n",
    "    print(tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
